<?php
namespace app\api\controller;

use Think\Db;
use app\common\logic\GoodsLogic;
use app\common\logic\OrderLogic;
use app\common\logic\UsersLogic;
use app\common\model\Order as OrderModel;
use think\Page;
class Order extends ApiBase {

    /**
     * 订单详情
     * @return mixed
     */
    public function orderDetail()
    {   
        $id    = input('order_id/d', 0);
        $Order = new OrderModel();
        $order = $Order::get(['order_id' => $id, 'user_id' => $this->user_id]);
        // p($order);
        if (!$order) {
            return $this->ajaxReturn([],0,'没有获取到订单信息');
        }
        foreach ($order['order_goods'] as $key => $value) {
            $order['order_goods'][$key]['goods_pic'] = goods_thum_images($value['goods_id'], 60, 60);
        }
        $data['order_goods']          = $order['order_goods'];
        $data['full_address']         = $order['full_address'];
        $data['order_status_detail']  = $order['order_status_detail'];
        $data['order_button']         = $order['order_button'];
        $data['add_time']             = date('Y-m-d H:i:s',$order['add_time']);
        $data['pay_status']           = $order['pay_status'];
        $data['user_note']            = $order['user_note'];
        $data['goods_price']          = $order['goods_price'];
        $data['shipping_price']       = $order['shipping_price'];
        $data['total_amount']         = $order['order_amount'];
        $data['order_id']             = $order['order_id'];
        $data['consignee']            = $order['consignee'];
        $data['mobile']               = $order['mobile'];
        $data['order_sn']             = $order['order_sn'];
        return $this->ajaxReturn($data);
    }

    /**
     * [order_list 订单列表]
     * @return [type] [description]
     */
    public function orderList(){
        $where = ' user_id=:user_id';
        $bind['user_id'] = $this->user_id;
        //条件搜索
       if(I('get.type')){
           $where .= C(strtoupper(I('get.type')));
       }
       // 搜索订单 根据商品名称 或者 订单编号
       $search_key = trim(I('search_key'));       
       if($search_key)
       {
          $where .= " and (order_sn like :search_key1 or order_id in (select order_id from `".C('database.prefix')."order_goods` where goods_name like :search_key2) ) ";
           $bind['search_key1'] = "%$search_key%";
           $bind['search_key2'] = "%$search_key%";
       }
        $where.=' and prom_type < 5 and deleted=0';//虚拟拼团订单不列出来
        $count = Db::name('order')->where($where)->bind($bind)->count();
        $Page = new Page($count,5);

        $show = $Page->show();
        $order_str = "order_id DESC";
        $orderList = Db::name('order')->order($order_str)->where($where)->bind($bind)->limit($Page->firstRow.','.$Page->listRows)->select();

        //获取订单商品
        $model = new UsersLogic();
        foreach($orderList as $k=>$v)
        {
            $orderList[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$orderList[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $orderList[$k]['goods_list'] = $data['result'];
            $orderList[$k]['add_time']   = date('Y-m-d H:i:s',$v['add_time']);
            $orderList[$k]['num']        = $data['num'];
            if($orderList[$k]['prom_type'] == 4){
                $pre_sell_item =  M('goods_activity')->where(array('act_id'=>$orderList[$k]['prom_id']))->find();
                $pre_sell_item = array_merge($pre_sell_item,unserialize($pre_sell_item['ext_info']));
                $orderList[$k]['pre_sell_is_finished']     = $pre_sell_item['is_finished'];
                $orderList[$k]['pre_sell_retainage_start'] = $pre_sell_item['retainage_start'];
                $orderList[$k]['pre_sell_retainage_end']   = $pre_sell_item['retainage_end'];
            }else{
                $orderList[$k]['pre_sell_is_finished'] = -1;//没有参与预售的订单
            }
            if ($v['order_status'] == 3 && ($v['pay_status'] == 1 || $v['pay_status'] == 4 || $v['pay_status'] == 3)) {
                $orderList[$k]['cancel_info'] = 1; // 取消订单详情
            }
        }

        if (!empty($orderList)) {
            $data['order_status']    = C('ORDER_STATUS');
            $data['shipping_status'] = C('SHIPPING_STATUS');
            $data['pay_status']      = C('PAY_STATUS');
            $data['list']            = $orderList;
            $data['active_status']   = I('get.type');
            return $this->ajaxReturn($data);
        }else{
            return $this->ajaxReturn([],0,'暂无数据');
        }

    }

    /**
     * 删除已取消的订单
     */
    public function orderDelete()
    {
        $user_id  = $this->user_id;
        $order_id = I('get.id/d');
        $order    = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        if (empty($order)) {
            return $this->ajaxReturn([],0,'订单不存在');
        }
        $res    = M('order')->where("order_id=$order_id and order_status=3")->delete();
        $result = M('order_goods')->where("order_id=$order_id")->delete();
        if ($res && $result) {
            return $this->ajaxReturn([],1,'操作成功');
        } else {
            return $this->ajaxReturn([],0,'操作失败');
        }
    }

    /**
     * 删除已完成订单
     */
    function delOrder(){
        $order_id = I('get.id/d');
        $store_id = I('get.store_id/d');
        $order = M('order')->where(array('order_id'=>$order_id))->find();
        if(empty($order)){
            return $this->ajaxReturn([],0,'订单不存在');
        }
        if($store_id!==false && $order['store_id']!=$store_id){
            return $this->ajaxReturn([],0,'此订单不属于当前店铺');
        }
        $orderMdl = model('Common/Order');
        if($store_id!==false){
            $result = $orderMdl->softDel($order_id);//店主删除订单采用软删除
        }
        if($result===false){
            return $this->ajaxReturn([],0,'操作失败');
        }
        return $this->ajaxReturn([],1,'操作成功');
    }

    
    public function payData(){
        $orderId    = input('order_id');
        $payType    = input('pay_type',0,'intval');
        
        $orderInfo  = model('Common/Order')->where(['order_id'=>$orderId])->find();
        if (!$orderInfo) {
            return $this->ajaxReturn([],0,'订单不存在');
        }

        if ($orderInfo['pay_status']>=1){
            return $this->ajaxReturn([],0,'该订单已经支付');
        }

        if ($payType == 1) {
            // 微信支付
            $result = $this->wxPay($orderInfo);
            if ($result['code']==1) {
                return $this->ajaxReturn($result['data']);
            }else{
                return $this->ajaxReturn([],0, $result['msg']);
            }
        }else{
            // 余额支付
            
        }
        
        
    }

    public function wxPay($orderInfo){
        $openId     = Db::name('users')->where('user_id', $this->user_id)->value('wxapp_openid');
        $jssdkLogic = model('Common/JssdkLogic','logic');
        $result     = $jssdkLogic->unifiedOrder($orderInfo,$openId,SITE_URL.url('Api/Payment/mobile_wxpay_notify_url'));
        if ($result['return_code'] == 'FAIL') {
            return ['code'=>0,'msg'=>$result['return_msg']];
        }

        //修改支付方式和 out_trade_no
        // $orderLogic->editPayName($orderId, $pay_type, $result['out_trade_no']);

        $data['appId']     = $result['appid'];
        $data['timeStamp'] = (string)time();
        $data['nonceStr']  = $result['nonce_str'];
        $data['package']   = "prepay_id=".$result['prepay_id'];
        $data['signType']  = 'MD5';
        $data['paySign']   = $jssdkLogic->makeSign($data);
        
        return ['code'=>1,'data'=>$data];
        // return $this->ajaxReturn($data);
    }

    /**
    * 取消订单
    */
    public function cancelOrder()
    {
        $id = I('get.id/d');
        //检查是否有积分，余额支付
        $logic = new OrderLogic();
        $data = $logic->cancel_order($this->user_id, $id);
        if($data['code']==1){
            return $this->ajaxReturn($data);
        }else{
            return $this->ajaxReturn([],0,$data['msg']);
        }
    }

    /**
     * 确定收货成功
     */
    public function orderConfirm()
    {
        $id = I('order_id/d', 0);
        $data = confirm_order($id, $this->user_id);

        if ($data['status'] != 1) {
            return $this->ajaxReturn([],0,$data['msg']);
        } else {
            $model = new UsersLogic();
            $order_goods = $model->get_order_goods($id);
            model('Common/UserMoneyLog')->editEstimate($data['order_sn']);
            return $this->ajaxReturn($order_goods);
        }
    }
}